<template>
  <el-config-provider namespace="ep" :locale="zhCn">
    <div class="app-wrapper">
      <template v-if="route.path === '/login' || route.path === '/forgetPassword'">
        <router-view></router-view>
      </template>
      <template v-else>
        <div class="app-container">
          <BaseHeader />
          <div class="main-container">
            <BaseSide :active-menu="activeMenu" @menu-click="addTab" />
            <div class="content-wrapper">
              <Tab 
                :tabs="tabs"
                :active-tab="activeMenu"
                @tab-click="tabClick"
                @tab-remove="handleTabRemove"
              />
              <div class="content-container">
                <router-view v-slot="{ Component }">
                  <keep-alive>
                    <component 
                      :is="Component"
                      :key="route.path"
                    />
                  </keep-alive>
                </router-view>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>
  </el-config-provider>
</template>

<script setup>
import { ref, onMounted, watch, markRaw } from 'vue';
import tab from './components/layouts/tab.vue';
import BaseSide from './components/layouts/BaseSide.vue';
import BaseHeader from './components/layouts/BaseHeader.vue';
import { useTabStore } from '~/stores/tabStore';
import { useRouter, useRoute } from 'vue-router';
import { House, Service, User, List, DataLine, Setting, Document, Calendar } from '@element-plus/icons-vue';
import zhCn from 'element-plus/dist/locale/zh-cn.mjs';

const tabStore = useTabStore();
const activeMenu = ref(tabStore.activeTab);
const activeTab = ref(tabStore.activeTab);
const tabs = ref(tabStore.tabs);
const router = useRouter();
const route = useRoute();

// 使用 markRaw 包装图标组件
const icons = {
  House: markRaw(House),
  Service: markRaw(Service),
  User: markRaw(User),
  List: markRaw(List),
  DataLine: markRaw(DataLine),
  Setting: markRaw(Setting),
  Document: markRaw(Document),
  Calendar: markRaw(Calendar)
};

// 监听路由变化
watch(() => route.path, (newPath) => {
  if (!newPath || route.meta.noTab) return;
  
  const currentTab = tabs.value.find(tab => tab.index === newPath);
  if (currentTab) {
    activeMenu.value = newPath;
    tabStore.switchTab(newPath);
  }
}, { immediate: true });

function addTab(menuItem) {
  if (!menuItem?.index || !menuItem?.name) return;
  
  const existingTab = tabs.value.find(tab => tab.index === menuItem.index);
  if (!existingTab) {
    tabs.value.push({
      name: menuItem.name,
      index: menuItem.index
    });
  }
  tabStore.switchTab(menuItem.index);
  updateActiveTab(menuItem.index);
}

function updateTabs(newTabs) {
  if (!Array.isArray(newTabs)) return;
  
  const updatedTabs = newTabs.length === 0 
    ? [{ name: '首页', index: '/' }] 
    : newTabs;
    
  tabs.value = updatedTabs;
  tabStore.tabs = updatedTabs;
}

function updateActiveTab(newActiveTab) {
  if (typeof newActiveTab !== 'string') return;
  
  tabStore.switchTab(newActiveTab);
  activeMenu.value = newActiveTab;
  router.push({ path: newActiveTab }).catch(() => {});
}

function tabClick(tab) {
  if (typeof tab !== 'string') return;
  
  activeMenu.value = tab;
  router.push({ path: tab }).catch(() => {});
}

function handleTabRemove(targetIndex) {
  if (!targetIndex) return;
  
  const tabIndex = tabs.value.findIndex(tab => tab.index === targetIndex);
  if (tabIndex === -1) return;
  
  // 如果关闭的是当前激活的标签，需要激活其他标签
  if (activeMenu.value === targetIndex) {
    const newActiveTab = tabs.value[tabIndex - 1] || tabs.value[tabIndex + 1];
    if (newActiveTab) {
      updateActiveTab(newActiveTab.index);
    }
  }
  
  // 从数组中移除标签
  tabs.value = tabs.value.filter(tab => tab.index !== targetIndex);
  tabStore.tabs = tabs.value;
}

onMounted(() => {
  if (!route.path || route.meta.noTab) return;

  try {
    // 获取当前路由对应的菜单项名称
    const currentPath = route.path;
    // tabs.value = initialTabs;
    // tabStore.tabs = initialTabs;
    tabStore.activeTab = currentPath;
    activeMenu.value = currentPath;
  } catch (error) {
    console.error('初始化路由标签失败:', error);
  }
});

</script>

<style>
/* 移除body的默认margin和padding */
body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

/* 应用根容器 */
.app-wrapper {
  @apply w-screen h-screen overflow-hidden;
}

/* 主应用容器 */
.app-container {
  @apply w-full h-full flex flex-col overflow-hidden;
}

/* 主内容区域 */
.main-container {
  @apply flex flex-1 overflow-hidden;
  height: calc(100vh - var(--ep-header-height));
}

/* 右侧内容区域包装器 */
.content-wrapper {
  @apply flex-1 flex flex-col bg-gray-100 overflow-hidden;
}

/* 实际内容区域 */
.content-container {
  @apply flex-1 p-3 relative;
  height: calc(100vh - var(--ep-header-height) - var(--ep-tabs-header-height));
  overflow-y: auto;
  overflow-x: hidden;
}

/* 自定义滚动条样式 */
.content-container::-webkit-scrollbar {
  @apply w-1.5;
}

.content-container::-webkit-scrollbar-track {
  @apply bg-transparent rounded-full;
}

.content-container::-webkit-scrollbar-thumb {
  @apply bg-gray-300 rounded-full transition-colors duration-300;
}

.content-container::-webkit-scrollbar-thumb:hover {
  @apply bg-gray-400;
}

/* 设置变量 */
:root {
  --ep-header-height: 60px;    /* 头部高度 */
  --ep-tabs-header-height: 40px;  /* Tab标签高度 */
}

/* 确保所有内容都在容器内 */
#app {
  @apply h-full overflow-hidden;
  color: var(--ep-text-color-primary);
}

/* 优化内容区域的滚动体验 */
.content-container {
  @apply scrollbar-thin scrollbar-track-transparent scrollbar-thumb-gray-300 hover:scrollbar-thumb-gray-400;
}
</style>
